import { Video, Sequence, interpolate, Audio, useCurrentFrame } from 'remotion';
import VideoText2 from './VideoText2';
import React from 'react';
import { Fragment } from 'react';
import type { Property } from 'csstype';
// 导入默认视频文件
import video1 from '../assets/movies/full-002.mp4';
import video2 from '../assets/movies/full-003.mp4';
import video3 from '../assets/movies/full-004.mp4';
import video4 from '../assets/movies/full-005.mp4';
import video5 from '../assets/movies/full-006.mp4';
import startVideo from '../assets/movies/full001.mp4';
import endVideo from '../assets/movies/full007.mp4';

// 导入默认音频文件
import audio1 from '../assets/audio/full-001.mp3';
import bgAudio from '../assets/audio/bg-m-1.mp3';

/* 分割音频 */
import marked2001 from '../assets/audio/marked-2-001.wav';
import marked2002 from '../assets/audio/marked-2-002.wav';
import marked2003 from '../assets/audio/marked-2-003.wav';
import marked3001 from '../assets/audio/marked-3-001.wav';
import marked3002 from '../assets/audio/marked-3-002.wav';
import marked4001 from '../assets/audio/marked-4-001.wav';
import marked4002 from '../assets/audio/marked-4-002.wav';

import marked5001 from '../assets/audio/marked-5-001.wav';
import marked5002 from '../assets/audio/marked-5-002.wav';
import marked5003 from '../assets/audio/marked-5-003.wav';
import marked5004 from '../assets/audio/marked-5-004.wav';
import marked5005 from '../assets/audio/marked-5-005.wav';
import marked6001 from '../assets/audio/marked-6-001.wav';
import marked7001 from '../assets/audio/marked-7-001.wav';
import marked7002 from '../assets/audio/marked-7-002.wav';

interface TextConfig {
  text?: string;
  style?: React.CSSProperties;
}

interface AudioConfig {
  audioUrl: string;
  volume?: number; // 音量 0-1
  text?: string; // 字幕文本
  duration?: number; // 音频持续时间(帧)
  highlightTexts?: string[]; // 添加这个属性
}

interface VideoConfig {
  videoUrl?: string;
  audios?: AudioConfig[]; // 改为支持多个音频配置
  duration?: number;
  rotation?: number;
  transition?: {
    enabled?: boolean;
    duration?: number;
  };
}

interface VideoData {
  video: string;
  audios?: AudioConfig[];
  highlightTexts?: string[];
  splitTexts?: string[];
  duration: number;
  rotation: number;
  transition: {
    enabled: boolean;
    duration: number;
  };
  animation?: boolean;
}

interface FullVideoMarkedProps {
  fps?: number;
  videoConfigs?: VideoConfig[];
}

export const FullVideoMarked: React.FC<FullVideoMarkedProps> = ({
  fps = 30,
  videoConfigs = [],
}) => {
  const frame = useCurrentFrame();

  const TEXT_DELAY = 15; // 0.5秒 = 15帧

  // 将 defaultVideoData 移到组件内部
  const defaultVideoData: VideoData[] = [
    {
      video: startVideo,
      audios: [
        {
          audioUrl: audio1,
          volume: 1.0,
          text: '预算二十多万  当然买林肯航海家了',
          highlightTexts: ['二十多万', '林肯航海家'],
          duration: 2.5 * fps, // 3秒
        },
      ],
      // text: '预算二十多万当然买林肯航海家了',
      highlightTexts: ['二十多万', '林肯航海家'],
      splitTexts: ['预算二十多万', '当然买林肯航海家了'],
      duration: 3 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
    {
      video: video1,
      audios: [
        {
          audioUrl: marked2001,
          volume: 1.0,
          text: '别人的高配也不过是它的标配',
          duration: 2 * fps, // 2秒
        },
        {
          audioUrl: marked2002,
          volume: 1.0,
          text: '2.0T四缸280匹马力',
          highlightTexts: ['2.0T四缸280匹马力'],
          duration: 2.24 * fps,
        },
        {
          audioUrl: marked2003,
          volume: 1.0,
          text: '车长4米9突出一个气势',
          highlightTexts: ['车长4米9'],
          duration: 2 * fps,
        },
      ],
      // text: '这一米多环抱大连屏，设计师你是不是五行缺屏啊',
      highlightTexts: ['2.0T四缸280匹马力', '车长4米9'],
      splitTexts: [
        '别人的高配也不过是它的标配',
        '2.0T四缸280匹马力',
        '车长4米9突出一个气势',
      ],
      duration: 7 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
    {
      video: video2,
      audios: [
        {
          audioUrl: marked3001,
          volume: 1.0,
          text: '这一米多环抱大连屏',
          duration: 1.7 * fps, // 2秒
          highlightTexts: ['环抱大连屏'],
        },
        {
          audioUrl: marked3002,
          volume: 1.0,
          text: '设计师你是不是五行缺屏啊',
          duration: 1.8 * fps,
        },
      ],
      // text: '这一米多环抱大连屏，设计师你是不是五行缺屏啊',
      highlightTexts: ['环抱大连屏'],
      splitTexts: ['这一米多环抱大连屏', '设计师你是不是五行缺屏啊'],
      duration: 4 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
    {
      video: video3,
      audios: [
        {
          audioUrl: marked4001,
          volume: 1.0,
          text: '这座椅这么宽敞',
          duration: 1.24 * fps, // 2秒
        },
        {
          audioUrl: marked4002,
          volume: 1.0,
          text: '还带电动调节舒服',
          duration: 1.8 * fps,
          highlightTexts: ['电动调节'],
        },
      ],
      animation: true,
      highlightTexts: ['电动调节'],
      splitTexts: ['这座椅这么宽敞', '还带电动调节', '舒服'],
      duration: 4 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
    {
      video: video4,
      audios: [
        {
          audioUrl: marked5001,
          volume: 1.0,
          text: '360全景标配',
          duration: 1.8 * fps, // 2秒
        },
        {
          audioUrl: marked5002,
          volume: 1.0,
          text: '一键泊车标配',
          duration: 1.26 * fps,
        },
        {
          audioUrl: marked5003,
          volume: 1.0,
          text: '盲区监测标配',
          duration: 1.4 * fps,
        },
        {
          audioUrl: marked5004,
          volume: 1.0,
          text: 'L2+驾驶辅助带车道居中',
          highlightTexts: ['L2+驾驶辅助'],
          duration: 2.34 * fps,
        },
        {
          audioUrl: marked5005,
          volume: 1.0,
          text: '还能自动变道',
          duration: 1.16 * fps,
          highlightTexts: ['自动变道'],
        },
      ],
      animation: true,
      highlightTexts: ['360全景标配'],
      splitTexts: [
        '360全景标配 一键泊车标配',
        '盲区监测标配',
        'L2+驾驶辅助带车道居中',
        '还能自动变道',
      ],
      duration: 8 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
    {
      video: video5,
      audios: [
        {
          audioUrl: marked6001,
          volume: 1.0,
          duration: 2.64 * fps,
          text: '你不会花30w还买不到这样的品质吧',
          highlightTexts: ['30w', '品质'],
        },
      ],
      // text: '你不会花30w还买不到这样的品质吧',
      // highlightTexts: ['30w', '品质'],
      splitTexts: ['你不会花30w还买不到这样的品质'],
      duration: 3 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
    {
      video: endVideo,
      audios: [
        {
          audioUrl: marked7001,
          volume: 1.0,
          duration: 1.26 * fps,
          text: '想知道最新落地价',
        },
        {
          audioUrl: marked7002,
          volume: 1.0,
          duration: 1.94 * fps,
          text: '抓紧来 找我拿全系报价吧',
        },
      ],
      splitTexts: ['想知道最新落地价', '抓进来找我拿全系报价吧'],
      duration: 3.5 * fps,
      rotation: 0,
      transition: { enabled: false, duration: 4 },
    },
  ];

  // 修复 sumTime 计算逻辑
  const sumTime = defaultVideoData.reduce((acc: number, curr: VideoData) => {
    if (!curr.audios) return acc;

    const audioDuration = curr.audios.reduce(
      (audioAcc: number, audio: AudioConfig) =>
        audioAcc + (audio.duration || 0),
      0,
    );

    return acc + audioDuration;
  }, 0);

  // Modify the mergedVideoData mapping
  const mergedVideoData = defaultVideoData.map((defaultItem, index) => {
    const customConfig = videoConfigs[index] || {};

    // 合并音频配置
    const mergedAudios = (customConfig.audios || defaultItem.audios || []).map(
      (audio) => ({
        ...audio,
        volume: audio.volume || 1.0,
        duration: audio.duration || 2 * fps, // 默认2秒如果没有指定
      }),
    );

    // 计算视频总时长为所有音频时长之和
    const totalAudioDuration = mergedAudios.reduce(
      (acc, audio) => acc + (audio.duration || 0),
      0,
    );

    return {
      ...defaultItem,
      video: customConfig.videoUrl || defaultItem.video,
      audios: mergedAudios,
      duration: totalAudioDuration, // 视频时长等于所有音频时长之和
      rotation: customConfig.rotation ?? defaultItem.rotation,
      transition: customConfig.transition ?? defaultItem.transition,
    };
  });

  // 添加总时长计算
  const totalDuration = mergedVideoData.reduce(
    (acc, curr) => acc + curr.duration,
    0,
  );

  // 在组件返回之前添加验证
  if (totalDuration <= 0) {
    console.error('Total duration must be greater than 0');
    return null;
  }

  const getVideoStyle = (
    rotation: number,
    index: number,
    isLast: boolean,
  ): React.CSSProperties => {
    const baseStyle = {
      objectFit: (index === 0 || isLast ? 'contain' : 'cover') as
        | 'contain'
        | 'cover',
      backgroundColor: index === 0 || isLast ? 'black' : 'transparent',
      willChange: 'transform',
    };

    if (rotation % 180 !== 0) {
      return {
        ...baseStyle,
        width: '100vh',
        height: '100vw',
        position: 'absolute' as const,
        top: '50%',
        left: '50%',
        transform: `rotate(${rotation}deg) translate(-50%, -50%)`,
        transformOrigin: '0 0',
      };
    }

    return {
      ...baseStyle,
      width: '100%',
      height: '100%',
      transform: 'none',
    };
  };

  // 添加更平滑的缓动函数
  const easeInOutCubic = (t: number) => {
    return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2;
  };

  const getTransitionStyles = (
    frame: number,
    start: number,
    currentVideoEnd: number,
    isLastVideo: boolean,
    videoTransition: VideoConfig['transition'],
  ) => {
    if (isLastVideo || !videoTransition?.enabled) {
      return {
        transform: 'translate3d(0, 0, 0)',
        willChange: 'transform',
        backfaceVisibility: 'hidden' as Property.BackfaceVisibility,
        WebkitBackfaceVisibility: 'hidden' as Property.BackfaceVisibility,
        transformStyle: 'preserve-3d' as Property.TransformStyle,
      };
    }

    const transitionDuration = videoTransition.duration || 4;
    const transitionStart = start + currentVideoEnd - transitionDuration;
    const isInTransition =
      frame >= transitionStart && frame < start + currentVideoEnd;

    if (!isInTransition) {
      return {
        transform: 'translate3d(0, 0, 0)',
        willChange: 'transform',
        backfaceVisibility: 'hidden' as Property.BackfaceVisibility,
        WebkitBackfaceVisibility: 'hidden' as Property.BackfaceVisibility,
        transformStyle: 'preserve-3d' as Property.TransformStyle,
      };
    }

    const progress = interpolate(
      frame - transitionStart,
      [0, transitionDuration],
      [0, 1],
      {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
        easing: easeInOutCubic,
      },
    );

    return {
      transform: `translate3d(${-100 * progress}%, 0, 0)`,
      willChange: 'transform, opacity',
      backfaceVisibility: 'hidden' as Property.BackfaceVisibility,
      WebkitBackfaceVisibility: 'hidden' as Property.BackfaceVisibility,
      transformStyle: 'preserve-3d' as Property.TransformStyle,
    };
  };

  const getNextVideoTransitionStyles = (
    frame: number,
    start: number,
    currentVideoEnd: number,
    videoTransition: VideoConfig['transition'],
  ) => {
    if (!videoTransition?.enabled) {
      return {
        display: 'none',
      };
    }

    const transitionDuration = videoTransition.duration || 4;
    const transitionStart = start + currentVideoEnd - transitionDuration;

    // 确保转场时机正确
    const isInTransition =
      frame >= transitionStart && frame < start + currentVideoEnd;

    if (!isInTransition) {
      return {
        transform: 'translate3d(100%, 0, 0)',
        willChange: 'transform',
      };
    }

    const progress = interpolate(
      frame - transitionStart,
      [0, transitionDuration],
      [0, 1],
      {
        extrapolateLeft: 'clamp',
        extrapolateRight: 'clamp',
        easing: easeInOutCubic,
      },
    );

    return {
      transform: `translate3d(${100 * (1 - progress)}%, 0, 0)`,
      willChange: 'transform',
    };
  };

  // 修改文字过渡效果函数
  const getTextTransitionStyles = (
    frame: number,
    start: number,
    currentVideoEnd: number,
    isLastVideo: boolean,
    videoTransition?: VideoConfig['transition'],
  ) => {
    const textStart = start + TEXT_DELAY;
    const transitionDuration = videoTransition?.duration || 8;

    const textEnd =
      isLastVideo || !videoTransition?.enabled
        ? start + currentVideoEnd
        : start + currentVideoEnd - transitionDuration;

    // 文字入场动画
    if (frame >= start && frame < textStart) {
      const enterProgress = interpolate(
        frame - start,
        [0, TEXT_DELAY],
        [0, 1],
        {
          extrapolateLeft: 'clamp',
          extrapolateRight: 'clamp',
          easing: easeInOutCubic,
        },
      );
      return {
        opacity: enterProgress,
        transform: `translateY(${20 * (1 - enterProgress)}px)`,
      };
    }

    // 文字退场动画
    if (frame >= textEnd && frame <= start + currentVideoEnd) {
      const exitProgress = interpolate(
        frame - textEnd,
        [0, transitionDuration],
        [0, 1],
        {
          extrapolateLeft: 'clamp',
          extrapolateRight: 'clamp',
          easing: easeInOutCubic,
        },
      );
      return {
        opacity: 1 - exitProgress,
        transform: `translateY(${20 * exitProgress}px)`,
      };
    }

    // 文字显示状态
    if (frame >= textStart && frame < textEnd) {
      return {
        opacity: 1,
        transform: 'translateY(0)',
      };
    }

    // 文字隐藏状态
    return {
      opacity: 0,
      transform: 'translateY(20px)',
    };
  };

  // 添加音量常量
  const BG_MUSIC_VOLUME = 0.7; // 背景音乐音量 30%
  const VOICE_VOLUME = 1.0; // 语音音量 100%

  return (
    <div
      style={{
        flex: 1,
        position: 'relative',
        overflow: 'hidden',
        backgroundColor: 'black',
        willChange: 'transform',
        backfaceVisibility: 'hidden' as Property.BackfaceVisibility,
        WebkitBackfaceVisibility: 'hidden' as Property.BackfaceVisibility,
        transformStyle: 'preserve-3d' as Property.TransformStyle,
      }}
    >
      {mergedVideoData.map((video, index) => {
        const isLastVideo = index === mergedVideoData.length - 1;
        const start = mergedVideoData
          .slice(0, index)
          .reduce((acc, curr) => acc + curr.duration, 0);
        const nextVideo =
          index < mergedVideoData.length - 1
            ? mergedVideoData[index + 1]
            : null;
        // 确保当前视频的持续时间包含了所有音频的时长
        const currentVideoEnd = video.duration;

        return (
          <Fragment key={index}>
            <Sequence
              from={start}
              durationInFrames={
                video.duration +
                (video.transition?.enabled ? video.transition.duration || 8 : 0)
              }
            >
              <div
                style={{
                  width: '100%',
                  height: '100%',
                  position: 'relative',
                  overflow: 'hidden',
                  backfaceVisibility: 'hidden' as Property.BackfaceVisibility,
                  WebkitBackfaceVisibility:
                    'hidden' as Property.BackfaceVisibility,
                  perspective: 1000,
                  transformStyle: 'preserve-3d' as Property.TransformStyle,
                  ...getTransitionStyles(
                    frame,
                    start,
                    currentVideoEnd,
                    isLastVideo,
                    video.transition,
                  ),
                }}
              >
                {/* 当前视频容器 */}
                <div
                  style={{
                    position: 'absolute',
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    transform: 'translate3d(0, 0, 0)',
                    backfaceVisibility: 'hidden' as Property.BackfaceVisibility,
                    WebkitBackfaceVisibility:
                      'hidden' as Property.BackfaceVisibility,
                    transformStyle: 'preserve-3d' as Property.TransformStyle,
                  }}
                >
                  <Video
                    muted
                    src={video.video}
                    style={{
                      ...getVideoStyle(
                        video.rotation,
                        index,
                        index === mergedVideoData.length - 1,
                      ),
                      backfaceVisibility:
                        'hidden' as Property.BackfaceVisibility,
                      WebkitBackfaceVisibility:
                        'hidden' as Property.BackfaceVisibility,
                    }}
                    preload="auto"
                  />
                </div>

                {/* 下一个视频容器 - 最后一个视频不需要 */}
                {nextVideo && !isLastVideo && (
                  <div
                    style={{
                      position: 'absolute',
                      width: '100%',
                      height: '100%',
                      display: 'flex',
                      alignItems: 'center',
                      justifyContent: 'center',
                      transform: 'translate3d(0, 0, 0)',
                      backfaceVisibility:
                        'hidden' as Property.BackfaceVisibility,
                      WebkitBackfaceVisibility:
                        'hidden' as Property.BackfaceVisibility,
                      ...getNextVideoTransitionStyles(
                        frame,
                        start,
                        currentVideoEnd,
                        video.transition,
                      ),
                    }}
                  >
                    <Video
                      muted
                      src={nextVideo.video}
                      style={{
                        ...getVideoStyle(
                          nextVideo.rotation,
                          index + 1,
                          index + 1 === mergedVideoData.length - 1,
                        ),
                        backfaceVisibility:
                          'hidden' as Property.BackfaceVisibility,
                        WebkitBackfaceVisibility:
                          'hidden' as Property.BackfaceVisibility,
                      }}
                    />
                  </div>
                )}

                {/* 预加载下一个视频 */}
                {nextVideo && (
                  <Video
                    src={nextVideo.video}
                    style={{ display: 'none' }}
                    muted
                  />
                )}

                {/* 文本容器 */}
                <div
                  style={{
                    position: 'absolute',
                    bottom: '20%',
                    left: 0,
                    right: 0,
                    zIndex: 2,
                    display: 'flex',
                    justifyContent: 'center',
                    alignItems: 'center',
                    padding: '0 20px',
                    ...getTextTransitionStyles(
                      frame,
                      start,
                      currentVideoEnd,
                      isLastVideo,
                      video.transition,
                    ),
                  }}
                >
                  <div
                    style={{
                      width: '100%',
                      textAlign: 'center',
                      transition: 'transform 0.3s ease-out',
                    }}
                  >
                    {/* <VideoTextMarked
                      splitTexts={[
                        {
                          text: '第一行文字',
                          startFrame: 0, // 从第 0 帧开始显示
                          duration: 90, // 显示 90 帧（约 3 秒）
                          fadeInDuration: 20, // 淡入用时 20 帧
                        },
                        {
                          text: '第二行文字',
                          startFrame: 30, // 从第 30 帧开始显示
                          duration: 120, // 显示 120 帧（约 4 秒）
                          fadeOutDuration: 30, // 淡出用时 30 帧
                        },
                        {
                          text: '第三行文字',
                          startFrame: 60, // 从第 60 帧开始显示
                          duration: 150, // 显示 150 帧（约 5 秒）
                        },
                      ]}
                      highlightTexts={video.highlightTexts}
                      style={{
                        ...(textConfigs[index]?.style || {}),
                        fontSize: '32px',
                        textShadow: '0 2px 4px rgba(0,0,0,0.5)',
                      }}
                    /> */}
                  </div>
                </div>
                {/* 修改音频播放逻辑 */}
                {video.audios?.map((audioConfig, audioIndex) => {
                  // 计算当前音频的开始时间（前面所有音频的持续时间之和）
                  const previousAudiosDuration =
                    video.audios
                      ?.slice(0, audioIndex)
                      .reduce((acc, audio) => acc + (audio.duration || 0), 0) ||
                    0;

                  return (
                    <Fragment key={audioIndex}>
                      <Sequence
                        from={previousAudiosDuration}
                        durationInFrames={audioConfig.duration || 2 * fps}
                      >
                        <Audio
                          src={audioConfig.audioUrl}
                          volume={audioConfig.volume || VOICE_VOLUME}
                        />
                        {audioConfig.text && (
                          <div
                            style={{
                              position: 'absolute',
                              bottom: '20%',
                              left: 0,
                              right: 0,
                              display: 'flex',
                              justifyContent: 'center',
                              alignItems: 'center',
                              color: 'white',
                              fontSize: '32px',
                              textShadow: '0 2px 4px rgba(0,0,0,0.5)',
                            }}
                          >
                            <VideoText2
                              text={audioConfig.text}
                              highlightTexts={audioConfig.highlightTexts}
                              style={{
                                textAlign: 'center',
                                padding: '10px 20px',
                              }}
                            />
                          </div>
                        )}
                      </Sequence>
                    </Fragment>
                  );
                })}
              </div>
            </Sequence>
          </Fragment>
        );
      })}
      {/* 背景音乐 - 调整音量 */}
      <Audio src={bgAudio} volume={BG_MUSIC_VOLUME} />
    </div>
  );
};

// 修改总时长计算，使用固定的 fps
// export const videoDuration = (6 + 8 + 5 + 4 + 24 + 12) * 30; // 总秒数 * 默认fps
